<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { optionApi } from '@T2/service/api.ts';
import { buildTree } from '@T2/utils/utils.ts';
import type Node from 'element-plus/es/components/tree/src/model/node';
import type { ElTree } from 'element-plus';

interface TreeNode {
  id: number;
  name: string;
  parent: null | number;
  project: number;
  children?: TreeNode[];
  [key: string]: any;
}

const props = withDefaults(defineProps<{
  option?: null | number;
  type?: '曲线分组';
}>(), {
  option: null,
  type: '曲线分组',
});
const emits = defineEmits<{
  (event: 'current-change', data: TreeNode | null, node: Node | null): void;
  (event: 'clear'): void;
}>();

onMounted(() => {
  getPosition();
});

const Resd = reactive({
  tree: [] as TreeNode[],
  optionID: props.option,
});
watch(() => props.option, (nv) => {
  Resd.optionID = nv;
  treeRef.value!.setCurrentKey(nv || undefined);
});
const getPosition = () => {
  Resd.tree = [];
  optionApi({
    method: 'get',
    params: {
      type: props.type,
    }
  }).then((res: any) => {
    Resd.tree = buildTree(res.results || [], 'parent');
    setTimeout(() => {
      treeRef.value!.setCurrentKey(props.option || undefined);
    }, 100);
  });
}

const treeRef = ref<InstanceType<typeof ElTree> | null>(null);
const filterNode = (value: string, data: TreeNode, node: Node) => {
  if (!value) {
    return true;
  }
  let obj = data, parentNode = node.parent, names: string[] = [];
  for(let level = node.level; level > 0; level--) {
    names = [...names, obj.name];
    obj = parentNode.data as TreeNode;
    parentNode = parentNode.parent;
  }
  return names.some(name => name.indexOf(value) !== -1);
}

const handleChange = (data: TreeNode | null, node: Node | null) => {
  emits('current-change', data, node);
}
const handleClear = () => {
  treeRef.value!.setCurrentKey()
  emits('clear');
}
</script>

<template>
  <el-tree-select
    ref="treeRef"
    node-key="id"
    :teleported="false"
    filterable
    clearable
    :highlight-current="true"
    :props="{label: 'name'}"
    v-model="Resd.optionID"
    :data="Resd.tree"
    :filter-node-method="filterNode"
    @current-change="handleChange"
    @clear="handleClear"
  />
</template>

<style lang="scss" scoped>

</style>

<style scoped>
:deep(.el-select-dropdown .el-icon) {
  font-size: 14px;
  margin-right: 5px;
}
:deep(.el-select-dropdown .el-tree-node__content) {
  height: 30px;
}
:deep(.el-select-dropdown .el-select-dropdown__item) {
  font-size: 15px;
}
</style>